var map = null;
var newControls = new Array();
var needLayers = new Array();
var myDis = null;
var measureAreaTool = null;
var myBearTool = null;
var drawingQuery = null;
var drawingManager = null;
var markerClustererYHD = null;
var markerClustererYFQ = null;
var markerClustererREC = null;
var markerClustererREC_0 = null;
var markerClustererREC_1 = null;

var pointLZArray = [];
var layer;
var addoverlay;
var tempid;
var tubiaodata;
var markerClustererQJ = null;
function InitMap_baidu() {
    layui.use('element', function () {
        var element = layui.element;

    });
    layui.use(['layer'], function () {
        layer = layui.layer;
    });

    map = new BMap.Map("allmap");
    var mapType1 = new BMap.MapTypeControl(
        {
            mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP],
            anchor: BMAP_ANCHOR_TOP_RIGHT
        }
    );
    map.addControl(mapType1);          //2D图，混合图
    map.enableScrollWheelZoom();   //启用滚轮放大缩小，默认禁用
    map.enableContinuousZoom();    //启用地图惯性拖拽，默认禁用
    var bdary = new BMap.Boundary();
    bdary.get("柳州市", function (rs) {       //获取行政区域
        var count = rs.boundaries.length; //行政区域的点有多少个
        if (count === 0) {
            return;
        }
        for (var i = 0; i < count; i++) {
            var ply = new BMap.Polygon(rs.boundaries[i], {strokeWeight: 2, strokeColor: "#ff0000", fillColor: ""}); //建立多边形覆盖物
            map.addOverlay(ply);  //添加覆盖物
            needLayers.push(ply);
            pointLZArray = pointLZArray.concat(ply.getPath());
        }
        map.setViewport(pointLZArray);    //调整视野
    });

    //初始化地图控件
    InitMapControls();
    //添加测量距离工具
    myDis = new BMapLib.DistanceTool(map);
    //添加测量面积工具
    measureAreaTool = createMeasureAreaTool(map);

    //添加测量方位工具
    myBearTool = new BMapLib.BearTool(map);

    $(".anchorBL").remove();


    //聚合
    markerClustererYHD = new BMapLib.MarkerClusterer(map, null);
    markerClustererYFQ = new BMapLib.MarkerClusterer(map, null);
    markerClustererREC = new BMapLib.MarkerClusterer(map, null);
    markerClustererREC_0 = new BMapLib.MarkerClusterer(map, null);
    markerClustererREC_1 = new BMapLib.MarkerClusterer(map, null);
    markerClustererQJ = new BMapLib.MarkerClusterer(map, null);

    layui.use('tree', function () {
        var tree = layui.tree;
        var yhdyear = [];
        var yfqyear = [];
        $.ajax({
            url: "/geoZhyfq/getYfqYear",
            type: 'GET',
            dataType: "json",
            async: false,
            success: function (data) {
                if (data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        yfqyear.push({
                            title: data[i] + "年度易发区",
                            id: data[i] + "年度易发区",
                        });

                    }
                }

            },
            error: function () {

            },
        });

        $.ajax({
            url: "/geoZhyhd/getYhdYear",
            type: 'GET',
            dataType: "json",
            async: false,
            success: function (data) {
                if (data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        yhdyear.push({
                            title: data[i] + "年度隐患点",
                            id: data[i] + "年度隐患点",
                        });

                    }
                }
            },
            error: function () {

            },
        });


        //渲染
        var inst1 = tree.render({
            elem: '#tree', //绑定元素
            showCheckbox: true,
            showLine: false,
            onlyIconControl: false,
            id: 'treeid',
            data: [
                {title: '乡镇边界'}, {title: '全景数据点'},
                {
                    title: '群测群防点',
                    id: 'yfq',
                    children: [{
                        title: '群众上报' //二级菜单
                    }, {
                        title: '日常巡查' //二级菜单
                    }],
                },

                {
                    title: '地质灾害易发区',
                    id: 'yfq',
                    children: yfqyear,
                },
                {title: '地质灾害隐患点', children: yhdyear, id: 'yhd'}],
            oncheck: function (obj) {

                var checkdata = {checked: obj.checked}
                if (obj.data.title == '乡镇边界') {
                    showLayerMap(checkdata, 0, "0");
                }
                if (obj.data.title == "地质灾害易发区") {
                    showLayerMap(checkdata, 1, "1970");
                }

                if (obj.data.title == "地质灾害隐患点") {
                    showLayerMap(checkdata, 2, "1970");
                }


                if (obj.data.title == "全景数据点") {
                    showLayerMap(checkdata, 3, "0");

                }

                if (obj.data.title.indexOf("年度易发区") != -1) {
                    showLayerMap(checkdata, 1, obj.data.title.substring(0, 4));
                }
                if (obj.data.title.indexOf("年度隐患点") != -1) {
                    showLayerMap(checkdata, 2, obj.data.title.substring(0, 4));
                }


                if (obj.data.title == "群测群防点") {
                    showLayerMap(checkdata, 4, "0");
                }


                if (obj.data.title == "群众上报") {
                    showLayerMap(checkdata, 5, "0");
                }

                if (obj.data.title == "日常巡查") {
                    showLayerMap(checkdata, 6, "0");
                }
            }
        });


    });


    layui.use('upload', function () {
        var upload = layui.upload;
        //执行实例
        var uploadInst = upload.render({
            elem: '#uploadPic' //绑定元素
            , url: '/upload/uploadFile'//上传接口
            , accept: 'images',
            done: function (res) {
                layui.use('layer', function () {
                    $("#uploaded-files").append(
                        $("<tr id='option" + res.list[0].id + "' data-id='" + res.list[0].id + "'/>")
                            .append($('<td/>').html("<img class='layui-upload-img' id='pic" + res.list[0].id + "' alt='" + res.list[0].fileName + "' src='/upload/downloadFile/" + res.list[0].id + "'  >"))
                            .append($('<td/>').html("<a onclick='deleteRow(" + res.list[0].id + ")'>删除</a>"))
                    );

                });
            }, before: function (obj) {

            }
            , error: function (err) {

                console.log(err)
                //请求异常回调
            }
        });
    });
    layui.use('upload', function () {
        var upload = layui.upload;
        //执行实例
        var uploadInst = upload.render({
            elem: '#yhd-uploadPic' //绑定元素
            , url: '/upload/uploadFile'//上传接口
            , accept: 'images',
            done: function (res) {
                layui.use('layer', function () {
                    $("#yhd-uploaded-files").append(
                        $("<tr id='option" + res.list[0].id + "' data-id='" + res.list[0].id + "'/>")
                            .append($('<td/>').html("<img class='layui-upload-img' id='pic" + res.list[0].id + "' alt='" + res.list[0].fileName + "' src='/upload/downloadFile/" + res.list[0].id + "'  >"))
                            .append($('<td/>').html("<a onclick='deleteRow(" + res.list[0].id + ")'>删除</a>"))
                    );

                });
            }, before: function (obj) {

            }
            , error: function (err) {

                console.log(err)
                //请求异常回调
            }
        });
    });


    $("#dropmenu").change(function () {
        var data = gettubiaodata();
        tianchongtubiao(data);
    });

}

function InitMapControls() {

    // 添加带有定位的导航控件
    var navigationControl = new BMap.NavigationControl({
        // 靠左上角位置
        anchor: BMAP_ANCHOR_TOP_LEFT,
        // LARGE类型
        type: BMAP_NAVIGATION_CONTROL_LARGE,
        // 启用显示定位
        enableGeolocation: true
    });
    map.addControl(navigationControl);
    //自定义控件


    //实例化鼠标绘制工具
    drawingManager = new BMapLib.DrawingManager(map, {
        isOpen: false, //是否开启绘制模式
        enableDrawingTool: true, //是否显示工具栏
        drawingToolOptions: {
            anchor: BMAP_ANCHOR_TOP_LEFT, //位置
            offset: new BMap.Size(100, 5), //偏离值
        },
        circleOptions: styleOptions, //圆的样式
        polylineOptions: styleOptions, //线的样式
        polygonOptions: styleOptions, //多边形的样式
        rectangleOptions: styleOptions //矩形的样式
    });
    //添加鼠标绘制工具监听事件，用于获取绘制结果
    drawingManager.addEventListener('overlaycomplete', addpoint);

    //实例化鼠标绘制工具
    drawingQuery = new BMapLib.DrawingManager(map, {
        isOpen: false, //是否开启绘制模式
        drawingMode: BMAP_DRAWING_RECTANGLE,
        enableDrawingTool: false, //是否显示工具栏
        rectangleOptions: styleOptions1 //矩形的样式
    });
    //添加鼠标绘制工具监听事件，用于获取绘制结果
    drawingQuery.addEventListener('overlaycomplete', Querycomplete);


    var Offset = new BMap.Size(100, 70);
    var backImg = "background: url('/static/images/删除.png') no-repeat center center;";
    newControl("清空", ClearNewLayer, Offset, backImg);
    //量测
    Offset = new BMap.Size(151, 70);
    backImg = "background: url('/static/images/测距.png') no-repeat center center;";
    newControl("距离量测", DistanceCL, Offset, backImg);
    Offset = new BMap.Size(202, 70);
    backImg = "background: url('/static/images/测面.png') no-repeat center center;";
    newControl("面积量测", AreaCL, Offset, backImg);
    Offset = new BMap.Size(253, 70);
    backImg = "background: url('/static/images/方位.png') no-repeat center center;";
    newControl("方位量测", BearCL, Offset, backImg);

    var Offset = new BMap.Size(100, 135);
    var backImg = "background: url('/static/images/拉框查询.png') no-repeat center center;";
    newControl("拉框查询", QueryByPullframe, Offset, backImg);
    var Offset = new BMap.Size(151, 135);
    var backImg = "background: url('/static/images/导入查询.png') no-repeat center center;";
    newControl("导入查询", openFile, Offset, backImg);
    var Offset = new BMap.Size(202, 135);
    var backImg = "background: url('/static/images/全局搜索.png') no-repeat center center;";
    newControl("全局搜索", SearchAll, Offset, backImg);


    map.addEventListener('rightclick', function (e) {
        if (e.overlay) {//判断右键单击的是否是marker
            return;
        }
        RightMapClick(e.point);
    });

}

// var overlays = [];
var overlaycomplete = function (e) {
    e.overlay.dataid = "new_-1";
    RightOverlayClick(e.overlay);
};


// var overlays = [];
var addpoint = function (e) {
    // overlays.push(e.overlay);
    e.overlay.dataid = "new_-1";
    drawingManager.close();
    drawingManager._map.enableDoubleClickZoom();
    RightOverlayClick(e.overlay);

};


var Qoverlays = [];
var Querycomplete = function (e) {
    // drawingQuery.close();
    if (Qoverlays.length > 0)
        map.removeOverlay(Qoverlays[Qoverlays.length - 1]);
    Qoverlays.push(e.overlay);

    e.overlay.dataid = "cx_-1";

    var strPolygon = "POLYGON((";//起始点要一致
    var fristPoint = [];
    for (let i = 0; i < e.overlay.zo.length; i++) {
        var lng = e.overlay.zo[i].lng;
        var lat = e.overlay.zo[i].lat;

        var bd09togcj02 = coordtransform.bd09togcj02(lng, lat);
        var gcj02towgs84 = coordtransform.gcj02towgs84(bd09togcj02[0], bd09togcj02[1]);
        if (i == 0)
            fristPoint = gcj02towgs84;
        strPolygon += gcj02towgs84[0] + " " + gcj02towgs84[1] + ",";
        //tempPoint.push(new BMap.Point(parseFloat(lng),parseFloat(lat)));
    }
    strPolygon += fristPoint[0] + " " + fristPoint[1];//添加第一点
    strPolygon += "))";
    getQContains(strPolygon);
};

function getQContains(strPolygon) {

    for (let i = 0; i < QResultOverlay.length; i++) {
        map.removeOverlay(QResultOverlay[i]);
    }
    QResultOverlay.length = 0;
    //绘制，显示

    layer.open({
        type: 1,
        title: '拉框查询',
        shade: false,
        offset: 'rb',
        maxmin: true,
        closeBtn: 1,
        area: ['100%', '48%'],
        content: $('#fenxitable'), cancel: function () {
            ClearNewLayer();
        }
    });
    document.getElementById("resultdiv").style.display = "block";
    document.getElementById("searchdiv").style.display = "none"; //隐藏

    var loading = gis_ContainsZhyfq(strPolygon);

    gis_ContainsZhyhd(strPolygon, loading);
}

function qingchu() {
    $("#keywords").val("");
    ClearNewLayer();
}

function searchBykeywords() {

    var keywords = $("#keywords").val();
    if (keywords == null || keywords.trim().length == 0) {
        layer.msg("搜索条件不能为空!");
        return;
    }
    document.getElementById("resultdiv").style.display = "block";
    document.getElementById("searchdiv").style.display = "block"; //隐藏

    var loading = getZhyfqByKeywords(keywords);
    getZhyhdByKeywords(keywords, loading);

}


function showQresult(hr, isLayer, flag) {

    for (let i = 0; i < hr.length; i++) {
        var strgeom = hr[i].geom;
        var index1 = strgeom.indexOf('(');
        var geomType = strgeom.substring(0, index1);
        if (geomType == "POINT") {
            strgeom = strgeom.substring(index1 + 1, strgeom.length - 1);
            var pointStr = strgeom.split(" ");
            DrawQResultPoint(pointStr, hr[i], isLayer, flag);
        }
        if (geomType == "POLYGON") {
            strgeom = strgeom.substring(index1 + 2, strgeom.length - 2);
            strgeom = strgeom.replace(/,/g, "\n");
            strgeom = strgeom.replace(/ /g, ",");
            if (isLayer) {
                DrawQResultPolygon(strgeom, styleOptions3, hr[i], isLayer);
            } else {
                DrawQResultPolygon(strgeom, styleOptions2, hr[i], isLayer);
            }


        }

    }

    if (flag == 1 || flag == 2) {
        appendData(hr, flag);
    }

}


function appendData(hr, flag) {
    layui.use('table', function () {

        if (flag == 1) {
            var wxh = 0;
            var wxr = 0;
            var wxj = 0;

            /*循环遍历hr  取需要汇总的数据*/
            if (hr != null) {
                if (hr.length > 0) {
                    for (var i = 0; i < hr.length; i++) {

                        if (isRealNum(parseInt(hr[i].wxH))) {
                            wxh = wxh + parseInt(hr[i].wxH);
                        }
                        if (isRealNum(parseInt(hr[i].wxR))) {
                            wxr = wxr + parseInt(hr[i].wxR);
                        }
                        if (isRealNum(parseInt(hr[i].wxJ))) {
                            wxj = wxj + parseInt(hr[i].wxJ);
                        }


                    }
                }
            }

            var cols = [[
                {field: "id", title: "ID", minWidth: 150},
                {field: "szXian", title: "县(区)", minWidth: 150},
                {field: "szXiang", title: "乡（镇、街道办）", minWidth: 150},
                {field: "szCun", title: "所在村", minWidth: 150},
                {field: "szTun", title: "所在屯", minWidth: 150},
                {field: "address", title: "地址", minWidth: 150},
                {field: "zhType", title: "易发灾种", minWidth: 150},
                {field: "wxH", title: "威胁房屋(户)", minWidth: 150},
                {field: "wxJ", title: "威胁房屋(间)", minWidth: 150},
                {field: "wxR", title: "威胁人口（人）", minWidth: 150},
                {field: "azd", title: "避灾安置点", minWidth: 150},
                {field: "wfYa", title: "有无应急预案表", minWidth: 150},
                {field: "zhMbk", title: "防灾明白卡（份）", minWidth: 150},
                {field: "bxMbk", title: "避险明白卡（份）", minWidth: 150},
                {field: "cunFzr", title: "村(社区)负责人", minWidth: 150},
                {field: "tel1", title: "电话号码", minWidth: 150},
                {field: "zhenFzr", title: "乡(镇/街道办)负责人", minWidth: 150},
                {field: "tel2", title: "电话号码", minWidth: 150},
                {field: "xianFzr", title: "县（区）负责人", minWidth: 150},
                {field: "tel3", title: "所在乡", minWidth: 150},
                {field: "bz", title: "备注", minWidth: 150}]];

            var table = layui.table;
            table.render({
                elem: "#res-yfq",
                cols: cols,
                data: hr,

                totalRow: {
                    'id': '汇总数据:',
                    'wxH': wxh,
                    'wxJ': wxj,
                    'wxR': wxr,
                }
                ,
                toolbar: '#toolbar'
                , defaultToolbar: ['filter', 'print', {
                    title: '导出' //标题
                    , layEvent: 'export' //事件名，用于 toolbar 事件中使用
                    , icon: 'layui-icon-export' //图标类名
                }, {
                    title: '分析' //标题
                    , layEvent: 'fenxi' //事件名，用于 toolbar 事件中使用
                    , icon: 'layui-icon-engine' //图标类名
                }], skin: 'line' //表格风格
                ,
                even: true
                ,
                page: true //是否显示分页
                ,
                limits: [5, 7, 10]
                ,
                limit: 5 //每页默认显示的数量

            });


            table.on('rowDouble(filter)', function (obj) {

                var arr = obj.data.geom.split(' ');
                var lat = arr[0].substring(6, arr[0].length)
                var lng = arr[1].substring(0, arr[1].length - 1);
                var point = new BMap.Point(lat, lng);
                var myIcon = new BMap.Icon("./imgs/points.png", new BMap.Size(100, 100));
                var marker2 = new BMap.Marker(point, {icon: myIcon});  // 创建标注
                map.addOverlay(marker2);

            });

        } else if (flag == 2) {

            var wxcc = 0;
            var ghfl = 0;
            var wxr = 0;


            if (hr != null) {
                if (hr.length > 0) {
                    for (var i = 0; i < hr.length; i++) {

                        if (isRealNum(parseInt(hr[i].wxCz))) {
                            wxcc = wxcc + parseInt(hr[i].wxCz);
                        }
                        if (isRealNum(parseInt(hr[i].ghFl))) {
                            ghfl = ghfl + parseInt(hr[i].ghFl);
                        }
                        if (isRealNum(parseInt(hr[i].wxR))) {
                            wxr = wxr + parseInt(hr[i].wxR);
                        }


                    }
                }
            }
            var cols = [[
                {field: "id", title: "ID", minWidth: 150},
                {field: "szXian", title: "县(区)", minWidth: 150},
                {field: "szXiang", title: "乡（镇、街道办）", minWidth: 150},
                {field: "szCun", title: "村（社区）", minWidth: 150},
                {field: "szTun", title: "屯", minWidth: 150},
                {field: "zdMc", title: "灾点名称", minWidth: 150},
                {field: "zdWz", title: "灾点位置", minWidth: 150},
                {field: "yhdType", title: "隐患点类型", minWidth: 150},
                {field: "fxDate", title: "发现时间", minWidth: 150},
                {field: "ghFl", title: "规模方量（m3）", minWidth: 150},
                {field: "yfYs", title: "引发因素", minWidth: 150},
                {field: "yfYy", title: "引发原因", minWidth: 150},
                {field: "wxR", title: "威胁人数（人）", minWidth: 150},
                {field: "wxCz", title: "威胁财产（万元）", minWidth: 150},
                {field: "xqJb", title: "险情级别", minWidth: 150},
                {field: "jcy", title: "监测员（群测人员）", minWidth: 150},
                {field: "tel1", title: "电话号码", minWidth: 150},
                {field: "cunFzr", title: "村级负责人", minWidth: 150},
                {field: "tel2", title: "电话号码", minWidth: 150},
                {field: "xiangFzr", title: "乡级负责人", minWidth: 150},
                {field: "tel3", title: "电话号码", minWidth: 150},
                {field: "xianFzr", title: "县级负责人", minWidth: 150},
                {field: "tel4", title: "电话号码", minWidth: 150},
                {field: "bz", title: "备注", minWidth: 150},

            ]];

            var table = layui.table;
            table.render({
                elem: '#res-yhd',
                cols: cols,
                totalRow: {
                    'id': '汇总数据:',
                    'wxCz': wxcc,
                    'ghFl': ghfl,
                    'wxR': wxr,
                }
                ,
                data: hr,
                toolbar: '#toolbar'
                , defaultToolbar: ['filter', 'print', {
                    title: '导出' //标题
                    , layEvent: 'daochu' //事件名，用于 toolbar 事件中使用
                    , icon: 'layui-icon-export' //图标类名
                }, {
                    title: '分析' //标题
                    , layEvent: 'fenxi' //事件名，用于 toolbar 事件中使用
                    , icon: 'layui-icon-engine' //图标类名
                }],
                skin: 'line' //表格风格
                ,
                even: true
                ,
                page: true //是否显示分页
                ,
                limits: [5, 7, 10]
                ,
                limit: 5 //每页默认显示的数量

            });


        }
        var table = layui.table;
        //监听事件
        table.on('toolbar(filter)', function (obj) {

            $('#dropmenu').html("");
            if (obj.event === 'export') { //提供工具栏导出按钮的点击事件
                var res = hr;
                if (res[0].id != 'ID') {
                    res.unshift({
                        id: 'ID',
                        szXian: '县(区)',
                        szXiang: '乡（镇、街道办）',
                        szCun: '村',
                        szTun: '屯',
                        address: '地理位置',
                        zhType: '易发灾种',
                        wxH: '威胁房屋-户',
                        wxJ: '威胁房屋-间',
                        wxR: '威胁人口（人）',
                        azd: '避灾安置点',
                        wfYa: '有无应急预案表',
                        zhMbk: '防灾明白卡（份）',
                        bxMbk: '避险明白卡（份）',
                        cunFzr: '村(社区)负责人',
                        tel1: '电话号码',
                        zhenFzr: '乡(镇/街道办)负责人',
                        tel2: '电话号码',
                        xianFzr: '县（区）负责人',
                        tel3: '电话号码',
                        bz: '备注',
                        geom: '坐标'
                    });
                }

                LAY_EXCEL.exportExcel(res, '易发区数据.xlsx', 'xlsx')
            }

            if (obj.event === 'daochu') { //提供工具栏导出按钮的点击事件
                var result = hr;
                if (result[0].id != 'ID') {
                    result.unshift({
                        id: 'ID',
                        szXian: '县(区)',
                        szXiang: '乡（镇、街道办）',
                        szCun: '村（社区）',
                        szTun: '屯',
                        zdMc: '灾点名称',
                        zdWz: '灾点位置',
                        yhdType: '隐患点类型',
                        fxDate: '发现时间',
                        ghFl: '规模方量（m3）',
                        yfYs: '引发因素',
                        yfYy: '引发原因',
                        wxDx: '威胁对象',
                        wxR: '威胁人数（人）',
                        wxCz: '威胁财产（万元）',
                        xqJb: '险情级别',
                        jcy: '监测员（群测人员）',
                        tel1: '电话号码',
                        cunFzr: '村级负责人',
                        tel2: '电话号码',
                        xiangFzr: '乡级负责人',
                        tel3: '电话号码',
                        xianFzr: '县级负责人',
                        tel4: '电话号码',
                        bz: '备注',
                        geom: '坐标'
                    });


                }
                LAY_EXCEL.exportExcel(result, '隐患点数据.xlsx', 'xlsx')

            }
            if (obj.event == 'fenxi') {
                tubiaodata = obj.config.data;
                var cols = obj.config.cols[0];
                for (var i = 0; i < cols.length; i++) {

                    $('#dropmenu').append('<option value="' + cols[i].field + '">' + cols[i].title + '</option>');


                }
                layer.open({
                    type: 1,
                    title: '数据汇总',
                    shade: false,
                    maxmin: true,
                    closeBtn: 1,
                    area: ['80%', '80%'],
                    content: $('#tubiao'), cancel: function () {

                    }
                });
                var data = gettubiaochushihuadata(cols[0].field);
                tianchongtubiao(data);

            }
        });
    });
}


var styleOptions = {
    strokeColor: "red",    //边线颜色。
    fillColor: "red",      //填充颜色。当参数为空时，圆形将没有填充效果。
    strokeWeight: 3,       //边线的宽度，以像素为单位。
    strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
    fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
    strokeStyle: 'solid' //边线的样式，solid或dashed。
}

var styleOptions1 = {
    strokeColor: "red",    //边线颜色。
    fillColor: "white",      //填充颜色。当参数为空时，圆形将没有填充效果。
    strokeWeight: 3,       //边线的宽度，以像素为单位。
    strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
    fillOpacity: 0.4,      //填充的透明度，取值范围0 - 1。
    strokeStyle: 'dashed' //边线的样式，solid或dashed。
}

var styleOptions2 = {
    strokeColor: "blue",    //边线颜色。
    fillColor: "red",      //填充颜色。当参数为空时，圆形将没有填充效果。
    strokeWeight: 3,       //边线的宽度，以像素为单位。
    strokeOpacity: 0.6,	   //边线透明度，取值范围0 - 1。
    fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
    strokeStyle: 'solid' //边线的样式，solid或dashed。
}

var styleOptions3 = {
    strokeColor: "blue",    //边线颜色。
    strokeWeight: 2,       //边线的宽度，以像素为单位。
    strokeOpacity: 0.5,	   //边线透明度，取值范围0 - 1。
    fillOpacity: 0.1,      //填充的透明度，取值范围0 - 1。
    strokeStyle: 'solid' //边线的样式，solid或dashed。
}

function newControl(name, clickFunc, defaultOffset, backImg) {
    // 定义一个控件类,即function
    function ZoomControl() {
        // 默认停靠位置和偏移量
        this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
        this.defaultOffset = defaultOffset;
    }

    // 通过JavaScript的prototype属性继承于BMap.Control
    ZoomControl.prototype = new BMap.Control();

    // 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回
    // 在本方法中创建个div元素作为控件的容器,并将其添加到地图容器中
    ZoomControl.prototype.initialize = function (map) {
        // 创建一个DOM元素
        var div = document.createElement("div");
        //解析Html串
        if (name == "导入查询") {
            var input = document.createElement("input");
            input.type = "file";
            input.accept = "text/plain";
            input.onchange = clickFunc;
            input.style = "opacity: 0;" +
                "height: 50px;" +
                "width: 50px;";
            div.appendChild(input);
        } else {
            div = document.createElement("div");
            div.style.cursor = "pointer";
            // 绑定事件,点击一次放大两级
            div.onclick = clickFunc;
        }

        // div = document.createElement("div");
        // div.style.cursor = "pointer";
        // // 绑定事件,点击一次放大两级
        // div.onclick =clickFunc;

        // 添加文字说明
        // div.appendChild(document.createTextNode(name));
        div.title = name;
        // 设置样式
        div.style =
            "height: 50px;" +
            "border: 1px solid #666;" +
            "border-radius: 5px;" +
            "overflow: hidden;" +
            "box-shadow: 1px 1px 3px rgba(0, 0, 0, 1);" +
            "float: left;" + backImg +
            "background-size: 80% 80%;" +
            "width: 50px;"
        ;

        // 添加DOM元素到地图中
        map.getContainer().appendChild(div);
        // 将DOM元素返回
        return div;
    }
    // 创建控件
    var myZoomCtrl = new ZoomControl();
    // 添加到地图当中
    map.addControl(myZoomCtrl);
    if (name != "清空覆盖")
        newControls.push(myZoomCtrl);
}

function ClearNewLayer() {
    var Lastindex = 1;
    while (map.getOverlays().length > needLayers.length) {
        var del = true;
        var tempLayer = map.getOverlays()[map.getOverlays().length - Lastindex];
        for (let j = 0; j < needLayers.length; j++) {
            if (needLayers[j] == tempLayer) {
                del = false;
                Lastindex++;
                break;
            }

        }
        if (del)
            map.removeOverlay(tempLayer);
    }

    drawingManager.close();
    drawingManager._map.enableDoubleClickZoom();

    drawingQuery.close();
    drawingQuery._map.enableDoubleClickZoom();
}

function ClearOverLayerById(layers, id) {
    for (let i = 0; i < layers.length; i++) {
        if (layers[i].dataid != null && layers[i].dataid == id) {
            map.removeOverlay(layers[i]);
            var temp = id.split('_');
            if (temp[0] == "yfq")
                markerClustererYFQ.removeMarker(layers[i]);
            else if (temp[0] == "yhd")
                markerClustererYHD.removeMarker(layers[i]);
            else if (temp[0] == "qj")
                markerClustererQJ.removeMarker(layers[i]);
            break;
        }
    }
}

//量测
function DistanceCL() {
    //开始测量
    myDis.open();
}

function AreaCL() {
    //面积测量
    measureAreaTool.open();
}

function BearCL() {
    myBearTool.open();
}

//查询
function QueryByPullframe() {
    drawingQuery.open();
// drawingQuery._bindRectangle();
    drawingQuery.setDrawingMode(BMAP_DRAWING_RECTANGLE);
}

//全局搜索
function SearchAll() {
    layer.open({
        type: 1,
        title: '全局搜索',
        shade: false,
        offset: 'rb',
        maxmin: true,
        closeBtn: 1,
        area: ['100%', '48%'],
        content: $('#fenxitable'), cancel: function () {
            ClearNewLayer();
        }
    });
    document.getElementById("resultdiv").style.display = "none";
    document.getElementById("searchdiv").style.display = "block"; //隐藏
}

var index = null;
var openFile = function (event) {
    // $("#coordText").html("");
    ClearNewLayer();

    var points = [];
    var input = event.target;
    var reader = new FileReader();
    reader.onload = function () {
        if (reader.result) {
            var allstr = reader.result;
            var strList = allstr.split('\n');
            var coordType = null;

            event.target.value = "";

            for (var i = 0; i < strList.length; i++) {
                if (i == 0) {
                    coordType = strList[i];
                    continue;
                }
                var lineStr = strList[i];
                var temp = lineStr.split(',');
                if (temp.length != 2) {
                    layer.msg("第" + (i + 1) + "行出现错误！");
                    return;
                }
                if (!myIsNaN(parseFloat(temp[0])) || !myIsNaN(parseFloat(temp[1]))) {
                    layer.msg("第" + (i + 1) + "行出现非数值型字符！");
                    return;
                }

                if (coordType.indexOf('直角') > -1) {
                    points.push(new BMap.Point(parseFloat(temp[1]), parseFloat(temp[0])));
                    // layer.msg("当前暂时只支持地理坐标！");
                    // return;
                } else if (coordType.indexOf('地理') > -1)
                    points.push(new BMap.Point(parseFloat(temp[0]), parseFloat(temp[1])));
                else {
                    layer.msg("坐标格式有误！");
                    return;
                }
            }


            if (coordType.indexOf('直角') > -1) {
                var tempPoint = [];
                for (var nP = 0; nP < points.length; nP++) {
                    var point = Xian80_To_WGS84(parseFloat(points[nP].lng), parseFloat(points[nP].lat), 0);
                    tempPoint.push(new BMap.Point(parseFloat(point.x), parseFloat(point.y)));
                }
                points = tempPoint;
            } else {

            }
            // baidu.maps.convertor.translate(points, 1,function(res) {
            //     var QBaiduCoords=[];
            //     $.map(res, function(p) {
            //         QBaiduCoords.push(p);
            //     });
            //     Qpolygon= new BMap.Polygon(QBaiduCoords, styleOptions1);
            //     Qpolygon.dataid ="cx_-1";
            //     map.addOverlay(Qpolygon);
            //     var pointArray=[];
            //     pointArray = pointArray.concat(Qpolygon.getPath());
            //     map.setViewport(pointArray);    //调整视野
            // });
            let BaiduMapPoints = [];
            for (let i = 0; i < points.length; i++) {
                var wgs84togcj02 = coordtransform.wgs84togcj02(points[i].lng, points[i].lat);
                var gcj02tobd09 = coordtransform.gcj02tobd09(wgs84togcj02[0], wgs84togcj02[1]);
                var BaiduMapPointTemp = new BMap.Point(parseFloat(gcj02tobd09[0]), parseFloat(gcj02tobd09[1]));
                BaiduMapPoints.push(BaiduMapPointTemp);
            }
            var QpolygonT = new BMap.Polygon(BaiduMapPoints, styleOptions1);
            map.addOverlay(QpolygonT);
            var pointArray = [];
            pointArray = pointArray.concat(QpolygonT.getPath());
            map.setViewport(pointArray);    //调整视野

            //查询
            let strPolygon = "POLYGON((";//起始点要一致
            for (let i = 0; i < points.length; i++) {
                strPolygon += points[i].lng + " " + points[i].lat + ",";
            }
            strPolygon += points[0].lng + " " + points[0].lat;//添加第一点
            strPolygon += "))";
            getQContains(strPolygon);
        }

    };
    reader.readAsText(input.files[0]);

};

var QResultOverlay = [];//保存查询对象
var QResultLayerXZQ = [];//保存行政区对象
function DrawQResultPolygon(coordText, Options, XMInfo, isLayer) {
    var BaiduMapPoints = [];
    var pointsTemp = coordText.split('\n');
    for (let i = 0; i < pointsTemp.length; i++) {
        var pointTemp = pointsTemp[i].split(',');
        var wgs84togcj02 = coordtransform.wgs84togcj02(pointTemp[0], pointTemp[1]);
        var gcj02tobd09 = coordtransform.gcj02tobd09(wgs84togcj02[0], wgs84togcj02[1]);
        var BaiduMapPointTemp = new BMap.Point(parseFloat(gcj02tobd09[0]), parseFloat(gcj02tobd09[1]));
        BaiduMapPoints.push(BaiduMapPointTemp);

        // var BaiduMapPointTemp = new BMap.Point(parseFloat(pointTemp[0]), parseFloat(pointTemp[1]));
        // BaiduMapPoints.push(BaiduMapPointTemp);
    }
    var QpolygonT = new BMap.Polygon(BaiduMapPoints, Options);
    QpolygonT.dataid = "xzq_" + XMInfo.id;
    map.addOverlay(QpolygonT);
    if (isLayer) {
        QResultLayerXZQ.push(QpolygonT);
    } else
        QResultOverlay.push(QpolygonT);

    RightOverlayClick(QpolygonT);

    addClickHandler(showFomaterInfo(XMInfo), QpolygonT);
    // baidu.maps.convertor.translate(BaiduMapPoints, 1,function(res) {
    //     var QResultBaiduCoords=[];
    //     $.map(res, function(p) {
    //         QResultBaiduCoords.push(p);
    //     });
    //     var QpolygonT = new BMap.Polygon(QResultBaiduCoords, Options);
    //     map.addOverlay(QpolygonT);
    //     QResultPolygon.push(QpolygonT);
    // });
}

var QResultLayerYFQ = [];//保存易发区对象
var QResultLayerYHD = [];//保存隐患点对象
var QResultLayerREC = [];//保存群测群防点对象
var QResultLayerREC_0 = [];//保存群测群防点对象(群众上报)
var QResultLayerREC_1 = [];//保存群测群防点对象(日常巡查)
var QResultLayerQJ = [];//保存全景点对象
function DrawQResultPoint(coordText, XMInfo, isLayer, flag) {
    var wgs84togcj02 = coordtransform.wgs84togcj02(coordText[0], coordText[1]);
    var gcj02tobd09 = coordtransform.gcj02tobd09(wgs84togcj02[0], wgs84togcj02[1]);

    var pt = new BMap.Point(parseFloat(gcj02tobd09[0]), parseFloat(gcj02tobd09[1]));

    if (flag == 1) {
        var myIcon = new BMap.Icon("/static/images/yfq.png", new BMap.Size(32, 32));
        var QMarkerT = new BMap.Marker(pt, {
            icon: myIcon
        });
        QMarkerT.dataid = "yfq_" + XMInfo.id;
        QMarkerT.nd = XMInfo.nd;


        if (isLayer)
            QResultLayerYFQ.push(QMarkerT);
        else {
            map.addOverlay(QMarkerT);
            QResultOverlay.push(QMarkerT);
        }

        RightOverlayClick(QMarkerT);
    } else if (flag == 2) {
        var myIcon = new BMap.Icon("/static/images/yhd.png", new BMap.Size(32, 32));
        var QMarkerT = new BMap.Marker(pt, {
            icon: myIcon
        });
        QMarkerT.dataid = "yhd_" + XMInfo.id;
        QMarkerT.nd = XMInfo.nd;
        if (isLayer)
            QResultLayerYHD.push(QMarkerT);
        else {
            map.addOverlay(QMarkerT);
            QResultOverlay.push(QMarkerT);
        }
        RightOverlayClick(QMarkerT);
    } else if (flag == 3) {
        var myIcon = new BMap.Icon("/static/images/qj.png", new BMap.Size(32, 32));
        var QMarkerT = new BMap.Marker(pt, {
            icon: myIcon
        });
        QMarkerT.dataid = "qj_" + XMInfo.id;
        if (isLayer)
            QResultLayerQJ.push(QMarkerT);
        else {
            map.addOverlay(QMarkerT);
            QResultOverlay.push(QMarkerT);
        }
    }

    else if (flag == 4) {

        var myIcon = new BMap.Icon("/static/images/rec.png", new BMap.Size(32, 32));
        var QMarkerT = new BMap.Marker(pt, {
            icon: myIcon
        });
        QMarkerT.dataid = "rec_" + XMInfo.id;
        if (isLayer)
            QResultLayerREC.push(QMarkerT);
        else {
            map.addOverlay(QMarkerT);
            QResultOverlay.push(QMarkerT);
        }
        RightOverlayClick(QMarkerT);
    } else if (flag === 5) {

        var myIcon = new BMap.Icon("/static/images/rec0.png", new BMap.Size(32, 32));
        var QMarkerT = new BMap.Marker(pt, {
            icon: myIcon
        });
        QMarkerT.dataid = "rec0_" + XMInfo.id;
        if (isLayer)
            QResultLayerREC_0.push(QMarkerT);
        else {
            map.addOverlay(QMarkerT);
            QResultOverlay.push(QMarkerT);
        }
        RightOverlayClick(QMarkerT);
    } else if (flag === 6) {

        var myIcon = new BMap.Icon("/static/images/rec1.png", new BMap.Size(32, 32));
        var QMarkerT = new BMap.Marker(pt, {
            icon: myIcon
        });
        QMarkerT.dataid = "rec1_" + XMInfo.id;
        if (isLayer)
            QResultLayerREC_1.push(QMarkerT);
        else {
            map.addOverlay(QMarkerT);
            QResultOverlay.push(QMarkerT);
        }
        RightOverlayClick(QMarkerT);
    }

    addClickHandler1(showFomaterInfo1(XMInfo, flag), QMarkerT);
}

function addClickHandler(content, polygon) {
    var infoWindow = new BMap.InfoWindow(content);  // 创建信息窗口对象
    var point = new BMap.Point(polygon.getBounds().getCenter().lng, polygon.getBounds().getCenter().lat)
    polygon.addEventListener("click", function () {
        map.openInfoWindow(infoWindow, point); //开启信息窗口
    });
}

function addClickHandler1(content, Marker) {
    var infoWindow = new BMap.InfoWindow(content);  // 创建信息窗口对象
    Marker.addEventListener("click", function () {
        map.openInfoWindow(infoWindow, Marker.point); //开启信息窗口
    });
}
function notNull(data) {
    if (data == null || data == undefined || data == "") {
        return " "
    } else {
        return data;
    }
}
function showFomaterInfo(xmInfo) {
    var sContent =
        "<p class='xmShow'><h4 style='text-align: center'>" + notNull(xmInfo.xzqmc) + "</h4></p>" +
        "<p></p>" +
        "<p class='xmShow'>行政区名称：" + notNull(xmInfo.xzqmc) + "</p>" +
        "<p class='xmShow'>所属区县：" + notNull(xmInfo.xianMc) + "</p>" +
        "<p class='xmShow'>行政区代码：" + notNull(xmInfo.xzqdm) + "</p>" +
        "<p class='xmShow'>县代码：" + notNull(xmInfo.xianDm) + "</p>" +
        "<p class='xmShow'><a href='#' onclick=\"showAllInfo(" + "" + ")\">查看详情</a></p>";
    return sContent;
}

function showFomaterInfo1(xmInfo, flag) {
    var sContent = "";
    if (flag == 1) {
        sContent =
            "<p class='xmShow'><h4 style='text-align: center'>地质灾害易发区：" + notNull(xmInfo.address) + "</h4></p>" +
            "<p></p>" +
            "<p class='xmShow'>灾害类型：" + notNull(xmInfo.zhType) + "</p>" +
            "<p class='xmShow'>安置点：" + notNull(xmInfo.azd) + "</p>" +
            "<p class='xmShow'>威胁人口（人）：" + notNull(xmInfo.wxR) + "</p>" +
            "<p class='xmShow'><button class='layui-btn layui-btn-sm layui-btn-danger' onclick=\"showYFQInfo(" + xmInfo.id + ",1)\">查看详情</button></p>";
        document.getElementById("uploadPic").style.display = "none"; //隐藏
        document.getElementById("tijiao").style.display = "none"; //隐藏


    } else if (flag == 2) {
        sContent =
            "<p class='xmShow'><h4 style='text-align: center'>地质灾害隐患点：" + xmInfo.zdMc + "</h4></p>" +
            "<p></p>" +
            "<p class='xmShow'>灾点位置：" + notNull(xmInfo.zdWz) + "</p>" +
            "<p class='xmShow'>隐患点类型：" + notNull(xmInfo.yhdType) + "</p>" +
            "<p class='xmShow'>险情级别：" + notNull(xmInfo.xqJb) + "</p>" +
            "<p class='xmShow'><button class='layui-btn layui-btn-sm layui-btn-danger' onclick=\"showYHDInfo(" + xmInfo.id + ",1)\">查看详情</button></p>";
        document.getElementById("yhd-uploadPic").style.display = "none"; //隐藏
        document.getElementById("yhd-tijiao").style.display = "none"; //隐藏

    } else if (flag == 3) {
        sContent =
            "<p class='xmShow'><h4 style='text-align: center'>全景：" + notNull(xmInfo.name) + "</h4></p>" +
            "<p></p>" +
            "<p class='xmShow'><a onclick='showQJ(\"" + xmInfo.fileid + "\",\"" + xmInfo.name + "\")'>查看全景</a></p>";
    } else if (flag == 4 || flag === 5 || flag === 6) {


        var sblx = "";
        if (xmInfo.type == 0) {
            sblx = "群众上报";
        } else {
            sblx = "日常巡查";
        }


        sContent =
            "<p class='xmShow'><h4 style='text-align: center'>群测群防点：" + xmInfo.id + "</h4></p>" +
            "<p></p>" +
            "<p class='xmShow'>上报类型：" + sblx + "</p>" +
            "<p class='xmShow'>地址：" + notNull(xmInfo.addressDetail) + "</p>" +
            "<p class='xmShow'>灾害描述：" + notNull(xmInfo.hazardDetail) + "</p>" +
            "<p class='xmShow'>巡查反馈：" + notNull(xmInfo.inspectionDetail) + "</p>" +
            "<p class='xmShow'>上报用户姓名：" + notNull(xmInfo.userName) + "</p>" +
            "<p class='xmShow'>联系电话：" + notNull(xmInfo.userPhone) + "</p>";
        if (xmInfo.status == 0) {
            sContent = sContent + "<p class='xmShow'><button class='layui-btn layui-btn-sm layui-btn-danger' onclick=\"showRecInfo(" + xmInfo.id + ")\">查看详情</button> <button class='layui-btn layui-btn-sm' onclick=\"editRecInfo(" + xmInfo.id + ")\">处理</button></p>";
        } else {
            sContent = sContent + "<p class='xmShow'><button class='layui-btn layui-btn-sm layui-btn-danger' onclick=\"showRecInfo(" + xmInfo.id + ")\">查看详情</button> <button class='layui-btn layui-btn-disabled'>已处理</button></p>";

        }

    }
    return sContent;
}

function showRecInfo(id) {
    document.getElementById("rectijiao").style.display = "none"; //隐藏
    RecInfo(id);

}

//显示全景
function showQJ(fileid, name) {
    var lIndex = layer.open({
        type: 2,
        title: name,
        shadeClose: false,
        shade: 0.5,
        maxmin: true,
        area: ['800px', '600px'],
        content: fileBaseUrl + "/dzQJ/" + fileid
    });
}

function editRecInfo(id) {
    document.getElementById("rectijiao").style.display = "block"; //隐藏
    RecInfo(id);
}

function RecInfo(id) {

    $.ajax({
        url: "/recordDO/getRecordById?id=" + id,
        type: 'GET',
        dataType: "json",
        async: false,
        success: function (res) {
            layer.open({
                type: 1,
                title: "群测群防点详情",
                area: ['80%', '80%'],
                content: $('#rec')
            });

            tianchongRec(res);
            var form = layui.form;
            form.render();

            /* 获取文件 */
            $.ajax({
                url: "/recordDO/getFilesByRecordId?id=" + id,
                type: 'GET',
                dataType: "json",
                success: function (data) {

                    $("#pic").html("");
                    if (data.length > 0) {
                        for (var j = 0; j < data.length; j++) {
                            $("#pic").append("<li><img src='/upload/downloadFile/" + data[j].id +
                                "'    data-original='/upload/downloadFile/" + data[j].id + "'   alt='" +
                                data[j].fileName + "'   /></li>");

                        }
                    }
                    var viewer = new Viewer(document.getElementById('pic'), {
                        toolbar: true, //显示工具条
                        viewed() {
                            viewer.zoomTo(1); // 图片显示比例 75%
                        },
                        show: function () { // 动态加载图片后，更新实例
                            viewer.update();
                        },
                    });

                },
                error: function () {

                },

            });


        },


    });

}


layui.use('form', function () {
    var form = layui.form;

    //监听提交
    form.on('submit(rec)', function (data) {
        //所有附件id集合
        var records = {
            "id": data.field.id,
            "status": data.field.status,
            "hazardType": data.field.hazardType,
            "hazardLevel": data.field.hazardLevel,
            "hazardScale": data.field.hazardScale,
            "hazardStatus": data.field.hazardStatus,
            "hazardDetail": data.field.hazardDetail,
            "inspectionStatus": data.field.inspectionStatus,
            "inspectionDetail": data.field.inspectionDetail,
            "remark": data.field.remark
        };
        var recordsdata = JSON.stringify(records);

        $.ajax({
            type: "post",
            dataType: "json",
            url: "/recordDO/editRecord",
            data: {
                "record": recordsdata
            },
            contentType: "application/x-www-form-urlencoded;charset=UTF-8",
            async: false,
            success: function (data) {

                if (data == true) {
                    layer.msg('修改成功!', {
                        icon: 1,
                        time: 800 //2秒关闭（如果不配置，默认是3秒）
                    }, function () {
                        layer.closeAll();
                    });
                } else {
                    layer.msg("修改失败!");
                }


            },
            error: function (data) {
                layer.msg("修改失败!");

            }
        });


        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });
});


function showYFQInfo(id, type) {
    if (id == undefined) {
        id = tempid;
    }

    var data = getInfoByZhyfqid(id);

    layer.open({
        type: 1,
        maxmin: true,
        shade: 0,
        area: ['70%', '80%'],
        size: 0,
        title: '地质灾害易发区信息',
        content: $('#addyfq') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
    });
    $("#uploaded-files").html("");
    $.ajax({
        url: "/geoZhyfq/getFileByZhyfqid?id=" + id,
        type: 'GET',
        dataType: "json",
        async: false,
        success: function (files) {
            if (files.length > 0) {
                for (var j = 0; j < files.length; j++) {
                    if (type == 1) {
                        $("#uploaded-files").append(
                            $("<tr id='option" + files[j].id + "' data-id='" + files[j].id + "'/>")
                                .append($('<td/>').html("<img class='layui-upload-img' id='pic" + files[j].id + "' alt='" + files[j].fileName + "' src='/upload/downloadFile/" + files[j].id + "'  >"))
                        );
                    }
                    if (type == 2) {
                        $("#uploaded-files").append(
                            $("<tr id='option" + files[j].id + "' data-id='" + files[j].id + "'/>")
                                .append($('<td/>').html("<img class='layui-upload-img' id='pic" + files[j].id + "' alt='" + files[j].fileName + "' src='/upload/downloadFile/" + files[j].id + "'  >"))
                                .append($('<td/>').html("<a onclick='deleteRow(" + files[j].id + ")'>删除</a>"))
                        );

                    }

                }
            }


        },
        error: function () {

        },

    });

    tianchong(data);
    var form = layui.form;
    form.render();

}

function showYHDInfo(id, type) {

    if (id == undefined) {
        id = tempid;
    }

    var data = getInfoByidZhyhd(id);

    layer.open({
        type: 1,
        maxmin: true,
        shade: 0,
        area: ['70%', '80%'],
        size: 0,
        title: '地质灾害隐患点信息',
        content: $('#addyhd') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
    });
    $("#yhd-uploaded-files").html("");
    $.ajax({
        url: "/geoZhyhd/getFileByZhyhdid?id=" + id,
        type: 'GET',
        dataType: "json",
        async: false,
        success: function (files) {
            if (files.length > 0) {
                for (var j = 0; j < files.length; j++) {
                    if (type == 1) {
                        $("#yhd-uploaded-files").append(
                            $("<tr id='option" + files[j].id + "' data-id='" + files[j].id + "'/>")
                                .append($('<td/>').html("<img class='layui-upload-img' id='pic" + files[j].id + "' alt='" + files[j].fileName + "' src='/upload/downloadFile/" + files[j].id + "'  >"))
                        );
                    }
                    if (type == 2) {
                        $("#yhd-uploaded-files").append(
                            $("<tr id='option" + files[j].id + "' data-id='" + files[j].id + "'/>")
                                .append($('<td/>').html("<img class='layui-upload-img' id='pic" + files[j].id + "' alt='" + files[j].fileName + "' src='/upload/downloadFile/" + files[j].id + "'  >"))
                                .append($('<td/>').html("<a onclick='deleteRow(" + files[j].id + ")'>删除</a>"))
                        );

                    }

                }
            }


        },
        error: function () {

        },

    });

    tianchongyhd(data);
    var form = layui.form;
    form.render();

}

function showAllInfo() {

}

function tianchongyhd(xq) {

    document.getElementById("addyhd").reset();
    $.ajax({
        url: 'http://116.8.3.172:8098/PersonManager/getPersonByYfqIdOrYhdId?yhdId=' + xq.id + "&&qx=" + xq.szXian,
        async: false,
        method: 'get',
        dataType: "json",
        contentType: 'application/text;charset=utf-8',
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                if (data[i].fzjb == "区/县级") {
                    $('#yhd-xianFzr').val(data[i].xm);
                    $('#yhd-tel4').val(data[i].tel/*.replace('.0', '')*/);
                }

                if (data[i].fzjb == "乡/镇/街道级") {
                    $('#yhd-xiangFzr').val(data[i].xm);
                    $('#yhd-tel3').val(data[i].tel/*.replace('.0', '')*/);
                }
                if (data[i].fzjb == "村/社区级") {
                    $('#yhd-cunFzr').val(data[i].xm);
                    $('#yhd-tel2').val(data[i].tel/*.replace('.0', '')*/);
                }
                if (data[i].fzjb == "灾害点/易发区级") {
                    $('#yhd-jcy').val(data[i].xm);
                    $('#yhd-tel').val(data[i].tel/*.replace('.0', '')*/);
                }

            }
        }
        ,
        error: function (ee) {
            debugger;
        }
    });

    $('#yhd-szXian').val(xq.szXian);
    $('#yhd-szXiang').val(xq.szXiang);
    $('#yhd-szCun').val(xq.szCun);
    $('#yhd-szTun').val(xq.szTun);
    $('#yhd-zdMc').val(xq.zdMc);
    $('#yhd-zdWz').val(xq.zdWz);
    $('#yhd-yhdType').val(xq.yhdType);
    $('#yhd-fxDate').val(xq.fxDate);
    $('#yhd-ghFl').val(xq.ghFl);
    $('#yhd-yfYs').val(xq.yfYs);
    $('#yhd-yfYy').val(xq.yfYy);
    $('#yhd-wxDx').val(xq.wxDx);
    $('#yhd-wxR').val(xq.wxR);
    $('#yhd-wxCz').val(xq.wxCz);
    $('#yhd-xqJb').val(xq.xqJb);
    $('#yhd-bz').val(xq.bz);

}


function tianchong(xq) {

    document.getElementById("addyfq").reset();
    $.ajax({
        url: 'http://116.8.3.172:8098/PersonManager/getPersonByYfqIdOrYhdId?yfqId=' + xq.id + "&&qx=" + xq.szXian,
        async: false,
        method: 'get',
        dataType: "json",
        contentType: 'application/text;charset=utf-8',
        success: function (data) {
            for (var i = 0; i < data.length; i++) {

                if (data[i].fzjb == "区/县级") {
                    $('#xianFzr').val(data[i].xm);
                    $('#tel3').val(data[i].tel/*.replace('.0', '')*/);
                }

                if (data[i].fzjb == "乡/镇/街道级") {
                    $('#zhenFzr').val(data[i].xm);
                    $('#tel2').val(data[i].tel/*.replace('.0', '')*/);
                }
                if (data[i].fzjb == "村/社区级") {
                    $('#cunFzr').val(data[i].xm);
                    $('#tel1').val(data[i].tel/*.replace('.0', '')*/);
                }


            }
        }
        ,
        error: function (ee) {
            debugger;
        }
    });

    $('#szXian').val(xq.szXian);
    $('#zhType').val(xq.zhType);
    $('#szXiang').val(xq.szXiang);
    $('#szCun').val(xq.szCun);
    $('#szTun').val(xq.szTun);
    $('#address').val(xq.address);
    $('#wxH').val(xq.wxH);
    $('#wxJ').val(xq.wxJ);
    $('#wxR').val(xq.wxR);
    $('#azd').val(xq.azd);
    $('#wfYa').val(xq.wfYa);
    $('#zhMbk').val(xq.zhMbk);
    $('#bz').val(xq.bz);
}

function tianchongRec(data) {
    /* 整合:处理人姓名应该获取 */
    $('#operatorName').val(data.operatorName);
    $('#type').val(data.type);
    $('#status').val(data.status);
    $('#userPhone').val(data.userPhone);
    $('#userName').val(data.userName);
    $('#city').val(data.city);
    $('#district').val(data.district);
    $('#street').val(data.street);
    $('#streetNumber').val(data.streetNumber);
    $('#hazardType').val(data.hazardType);
    $('#hazardLevel').val(data.hazardLevel);
    $('#hazardScale').val(data.hazardScale);
    $('#hazardStatus').val(data.hazardStatus);
    $('#hazardDetail').val(data.hazardDetail);
    $('#feedback').val(data.feedback);
    $('#inspectionStatus').val(data.inspectionStatus);
    $('#inspectionDetail').val(data.inspectionDetail);
    $('#remark').val(data.remark);
    $('#id').val(data.id);
    $('#createTime').val(data.createTime);
}


//右键单击Maker出现右键菜单事件
function RightOverlayClick(overlay) {
    /*  var markerMenu = new BMap.ContextMenu();
     // markerMenu.addItem(new BMap.MenuItem('查看附近资源',watchOverlay.bind(overlay)));
     for (var i = 0; i < txtMenuOverlayItem.length; i++) {
     if (txtMenuOverlayItem[i].text.indexOf("保存") > -1) {
     if (overlay.dataid.indexOf("new_") == -1) {
     continue;
     }
     }
     if (txtMenuOverlayItem[i].text == "编辑" || txtMenuOverlayItem[i].text == "删除") {
     if ((overlay.dataid.indexOf("yhd_") == -1) && (overlay.dataid.indexOf("yfq_") == -1)) {
     continue;
     }
     }
     var MenuItem = new BMap.MenuItem(txtMenuOverlayItem[i].text, txtMenuOverlayItem[i].callback, 100);
     markerMenu.addItem(MenuItem);

     }
     overlay.addContextMenu(markerMenu);//给标记添加右键菜单*/
}

/*var txtMenuOverlayItem = [  //右键菜单项目
 {
 text: '保存为隐患点',
 callback: function (e, d, overlay) {
 $("#yhd-uploaded-files").html("");
 document.getElementById("yhd-uploadPic").style.display = "block"; //显示
 document.getElementById("yhd-tijiao").style.display = "block"; //隐藏
 document.getElementById("yhd-addbtn").style.display = "block"; //隐藏
 document.getElementById("yhd-editbtn").style.display = "none"; //隐藏
 $("#addyhd")[0].reset();
 layui.form.render();

 addoverlay = overlay;
 layer.open({
 type: 1,
 shade: 0,
 area: ['70%', '80%'],
 size: 0,
 title: '填写地质灾害隐患点信息',
 content: $('#addyhd') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
 });

 }
 },
 {
 text: '保存为易发区',
 callback: function (e, d, overlay) {

 $("#uploaded-files").html("");
 document.getElementById("uploadPic").style.display = "block"; //显示
 document.getElementById("tijiao").style.display = "block"; //隐藏
 document.getElementById("addbtn").style.display = "block"; //隐藏
 document.getElementById("editbtn").style.display = "none"; //隐藏
 $("#addyfq")[0].reset();
 layui.form.render();

 addoverlay = overlay;
 layer.open({
 type: 1,
 shade: 0,
 area: ['70%', '80%'],
 size: 0,
 title: '填写地质灾害易发区信息',
 content: $('#addyfq') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
 });
 }
 },
 {
 text: '编辑',
 callback: function (e, d, overlay) {
 var temp = overlay.dataid.split('_');
 if (temp[0] == "yhd") {
 addoverlay = overlay;
 tempid = temp[1];
 showYHDInfo(temp[1], 2);
 document.getElementById("yhd-uploadPic").style.display = "block"; //显示
 document.getElementById("yhd-tijiao").style.display = "block"; //隐藏
 document.getElementById("yhd-addbtn").style.display = "none"; //隐藏
 document.getElementById("yhd-editbtn").style.display = "block"; //隐藏

 } else if (temp[0] == "yfq") {
 addoverlay = overlay;
 tempid = temp[1];
 showYFQInfo(temp[1], 2);
 document.getElementById("uploadPic").style.display = "block"; //显示
 document.getElementById("tijiao").style.display = "block"; //隐藏
 document.getElementById("addbtn").style.display = "none"; //隐藏
 document.getElementById("editbtn").style.display = "block"; //隐藏

 }

 }
 },
 {
 text: '删除',
 callback: function (e, d, overlay) {
 layer.confirm('是否确定删除？', {
 btn: ['不删除', '删除'] //按钮
 }, function () {
 layer.msg('没有删除！');
 }, function () {
 var temp = overlay.dataid.split('_');
 var hr = false;
 if (temp[0] == "yhd") {
 hr = delete1Zhyhd(temp[1]);
 } else if (temp[0] == "yfq") {
 hr = delete1Zhyfq(temp[1]);
 }
 if (hr) {
 if (temp[0] == "yhd") {
 ClearOverLayerById(QResultLayerYHD, overlay.dataid);
 } else if (temp[0] == "yfq") {
 ClearOverLayerById(QResultLayerYFQ, overlay.dataid);
 }
 layer.msg("删除成功！");
 layer.closeAll();
 }
 else
 layer.msg("删除失败！");
 });


 }
 }
 ];*/
function RightMapClick(p) {
    var markerMenu = new BMap.ContextMenu();
    for (var i = 0; i < txtMenuMapItem.length; i++) {
        var MenuItem = new BMap.MenuItem(txtMenuMapItem[i].text, txtMenuMapItem[i].callback, 100);
        markerMenu.addItem(MenuItem);//EventMarker.bind(i)
        //MenuItem(text: String 设置菜单项的icon, callback: Function 事件, opts: MenuItemOptions)
        //MenuItemOptions
        //width   Number	指定此菜单项的宽度，菜单以最长的菜单项宽度为准
        //id      String    指定此菜单项dom的id
        //iconUrl String | ContextMenuIcon  指定此菜单项的icon URL（大小为17px*17px）

        //ContextMenuIcon
        //BMAP_CONTEXT_MENU_ICON_ZOOMIN	 放大图标
        //BMAP_CONTEXT_MENU_ICON_ZOOMOUT 缩小图标

    }
    map.addContextMenu(markerMenu);//添加右键菜单
}

var txtMenuMapItem = [  //右键菜单项目
    {
        text: '放大',
        callback: function () {
            map.zoomIn()
        }
    },
    {
        text: '缩小',
        callback: function () {
            map.zoomOut()
        }
    },
    {
        text: '缩放到柳州',
        callback: function () {
            map.setViewport(pointLZArray)
        }
    }
];


function showLayerMap(self, type, nd) {

    if (type == 0) {//乡镇行政区划
        if (self.checked) {
            var hr = getAllXzqxian({});
            showQresult(hr, true, type);
        } else {
            for (let i = 0; i < QResultLayerXZQ.length; i++) {
                map.removeOverlay(QResultLayerXZQ[i]);
            }
            QResultLayerXZQ.length = 0;
        }
    } else if (type == 1) {//地质灾害易发区
        if (self.checked) {
            getZhyfqByNd(nd, type, 1);
        } else {

            var tempQResultLayerYFQ = [];
            var length = 0;
            for (let i = 0; i < QResultLayerYFQ.length; i++) {

                if (QResultLayerYFQ[i].nd == nd || nd == "1970") {
                    map.removeOverlay(QResultLayerYFQ[i]);
                    tempQResultLayerYFQ.push(QResultLayerYFQ[i]);
                    length = length + 1;
                }
            }
            markerClustererYFQ.removeMarkers(tempQResultLayerYFQ);
            QResultLayerYFQ.length = QResultLayerYFQ.length - length;


        }

    } else if (type == 2) {//地质隐患点
        if (self.checked) {
            getZhyhdByNd(nd, type,1);
        } else {
            var tempQResultLayerYHD = [];
            var length = 0;
            for (let i = 0; i < QResultLayerYHD.length; i++) {

                if (QResultLayerYHD[i].nd == nd || nd == "1970") {
                    map.removeOverlay(QResultLayerYHD[i]);
                    tempQResultLayerYHD.push(QResultLayerYHD[i]);
                    length = length + 1;
                }
            }
            markerClustererYHD.removeMarkers(tempQResultLayerYHD);
            QResultLayerYHD.length = QResultLayerYHD.length - length;
        }
    } else if (type == 3) {//全景
        if (self.checked) {
            var hr = GetAllQJ({});
            showQresult(hr, true, type);
            markerClustererQJ.addMarkers(QResultLayerQJ);
        } else {
            markerClustererQJ.removeMarkers(QResultLayerQJ);
            for (let i = 0; i < QResultLayerQJ.length; i++) {
                map.removeOverlay(QResultLayerQJ[i]);
            }
            QResultLayerQJ.length = 0;
        }

    } else if (type == 4) {//群测群防点
        if (self.checked) {
            var hr = getAllRecord();

            showQresult(hr, true, type);
            markerClustererREC.addMarkers(QResultLayerREC);
        } else {
            markerClustererREC.removeMarkers(QResultLayerREC);
            for (let i = 0; i < QResultLayerREC.length; i++) {
                map.removeOverlay(QResultLayerREC[i]);
            }
            QResultLayerREC.length = 0;
        }

    } else if (type === 5) {
        // 群众上报
        if (self.checked) {
            var hr = getRecordByType(0);

            showQresult(hr, true, type);
            markerClustererREC_0.addMarkers(QResultLayerREC_0);
        } else {
            markerClustererREC_0.removeMarkers(QResultLayerREC_0);
            for (let i = 0; i < QResultLayerREC_0.length; i++) {
                map.removeOverlay(QResultLayerREC_0[i]);
            }
            QResultLayerREC_0.length = 0;
        }
    } else if (type === 6) {
        // 日常巡查
        if (self.checked) {
            var hr = getRecordByType(1);

            showQresult(hr, true, type);
            markerClustererREC_1.addMarkers(QResultLayerREC_1);
        } else {
            markerClustererREC_1.removeMarkers(QResultLayerREC_1);
            for (let i = 0; i < QResultLayerREC_1.length; i++) {
                map.removeOverlay(QResultLayerREC_1[i]);
            }
            QResultLayerREC_1.length = 0;
        }
    }
}


function deleteRow(id) {
    $("#option" + id).remove();
}

function getAttachmentIds() {
    var ids = new Array();
    $("#uploaded-files tr").each(function () {
        ids.push($(this).attr("data-id"));
    });
    return ids;
}

function getyhdAttachmentIds() {
    var ids = new Array();
    $("#yhd-uploaded-files tr").each(function () {
        ids.push($(this).attr("data-id"));
    });
    return ids;
}

function gettubiaodata() {

    var objS = document.getElementById("dropmenu");
    var field = objS.options[objS.selectedIndex].value;
    var legendData = [];
    var seriesData = [];
    for (var i = 0; i < tubiaodata.length; i++) {

        var flag = true;
        if (seriesData.length > 0) {
            for (var j = 0; j < seriesData.length; j++) {

                if (tubiaodata[i][field] != undefined) {

                    if (tubiaodata[i][field] == seriesData[j].name) {
                        flag = false;
                    }
                }
            }
        }


        if (flag) {
            var value = 0;
            for (var k = 0; k < tubiaodata.length; k++) {
                if (tubiaodata[k][field] == tubiaodata[i][field]) {
                    value = value + 1;
                }

            }

            legendData.push(tubiaodata[i][field]);
            seriesData.push({
                name: tubiaodata[i][field],
                value: value


            });
        }


    }
    return {
        legendData: legendData,
        seriesData: seriesData,
    };

}

function tianchongtubiao(data) {
    var myChart = echarts.init(document.getElementById('bingtu'));
    option = {
        title: {
            text: '',
            subtext: '',
            left: 'center'
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 10,
            top: 20,
            bottom: 20,
            data: data.legendData,
        },
        series: [
            {
                name: '',
                type: 'pie',
                radius: '55%',
                center: ['40%', '60%'],
                data: data.seriesData,
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };

    myChart.setOption(option);
}


function gettubiaochushihuadata(field) {

    var legendData = [];
    var seriesData = [];
    for (var i = 0; i < tubiaodata.length; i++) {
        var value;
        value = 1;
        legendData.push(tubiaodata[i][field]);
        seriesData.push({
            name: tubiaodata[i][field],
            value: value
        });

    }
    return {
        legendData: legendData,
        seriesData: seriesData,
    };

}
